package com.cnbot.dchttpsdk.interceptor;

import android.util.Log;

import com.cnbot.dchttpsdk.helper.DownFileProgressListener;
import com.cnbot.dchttpsdk.helper.ProgressResponseBody;
import com.cnbot.dchttpsdk.utils.NetUtil;

import java.io.IOException;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Copyright (c) 2016-a  Hunan Cnbot Co., Ltd. All Rights Reserved.
 *
 * @descriptoin 拦截器
 * @FileName: CacheControlInterceptor.java
 * @author: dc
 * @date: 2019/1/19 14:10
 * @version: 1.0
 */

public class CacheControlInterceptor implements Interceptor {

    private static final String TAG = "CacheControlInterceptor";

    /**
     * 短缓存有效期为1分钟
     */
    public static final int CACHE_STALE_SHORT = 60;
    /**
     * 长缓存有效期为7天
     */
    public static final int CACHE_STALE_LONG = 60 * 60 * 24 * 7;

    public static final String CACHE_CONTROL_AGE = "Cache-Control: public, max-age=";

    /**
     * 查询缓存的Cache-Control设置，为if-only-cache时只查询缓存而不会请求服务器，max-stale可以配合设置缓存失效时间
     */
    public static final String CACHE_CONTROL_CACHE = "only-if-cached, max-stale=" + CACHE_STALE_LONG;
    /**
     * 查询网络的Cache-Control设置，头部Cache-Control设为max-age=0时则不会使用缓存而请求服务器
     */
    public static final String CACHE_CONTROL_NETWORK = "max-age=0";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (!NetUtil.isNetworkConnected()) {
            request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
        }
        Response originalResponse = chain.proceed(request);

        if (NetUtil.isNetworkConnected()) {
            //有网的时候读接口上的@Headers里的配置，你可以在这里进行统一的设置
            String cacheControl = request.cacheControl().toString();
            return originalResponse.newBuilder().header("Cache-Control", cacheControl).removeHeader("Pragma").build();
        } else {
            return originalResponse.newBuilder().body(new ProgressResponseBody(originalResponse.body(), new DownFileProgressListener() {
                @Override
                public void onProgress(long progress, long total, boolean isDone) {
                    Log.e(TAG, "onProgress: " + "total ---->" + total + "done ---->" + progress);
                }
            })).header("Cache-Control", "public, only-if-cached, max-stale=" + CACHE_STALE_LONG).removeHeader("Pragma").build();
        }
    }

}